<template>
  <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" size="small">
    <el-row>
      <el-col :md="12">
        <el-form-item label="活动名称" prop="rechargeActivityName">
          <el-input v-model.trim="ruleForm.rechargeActivityName" placeholder="请输入活动名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :md="12">
        <el-form-item label="活动时间" prop="_dateRange">
          <el-date-picker
            size="small"
            v-model="ruleForm._dateRange"
            type="datetimerange"
            range-separator="-"
            start-placeholder="活动开始日期"
            end-placeholder="活动结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="优惠配置" prop="rechargeDiscountList">
      <el-button type="text" style="padding: 0" @click="handleAddClick">
        <i class="el-icon-plus" style="font-size:14px;" />
      </el-button>
    </el-form-item>

    <div class="v-one-to-many__subWrapper recharge">
      <SubForm
        v-for="(key) in itemMap"
        :key="key.uuid"
        :uuid="key.uuid"
        :closable="itemMap.length > 1"
      />
    </div>

    <el-form-item label="活动图片" prop="rechargeActivityPicture">
      <el-input v-model="ruleForm.rechargeActivityPicture" class="hide" />
      <el-upload
        :action="$V.uploadURL"
        :headers="{token: $getToken()}"
        :on-success="(...args) => handleUploadSuccess('rechargeActivityPicture', ...args)"
        :on-remove="(...args) => handleUploadRemove('rechargeActivityPicture', ...args)"
        :on-error="handleUploadError"
        :file-list="rechargeFileList"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>

    <el-form-item label="活动内容" prop="rechargeActivityContent">
      <t-editor v-model.trim="ruleForm.rechargeActivityContent" validateEvent></t-editor>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit">{{actionText}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
/* Mixins
------------------------------- */
import { Form, Emitter } from '@/mixins'

/* Components
------------------------------- */
import TEditor from '@/components/editor/Editor'
import SubForm from './RechargeSubForm'
/* Api
------------------------------- */

/* Model
------------------------------- */
import { rechargeModel, primaryKey } from '../model'

let seed = 1

export default {
  componentName: 'RechargeForm',
  mixins: [Form('ruleForm', rechargeModel), Emitter],
  components: {
    TEditor,
    SubForm
  },
  data () {
    return {
      // 子表集合
      itemMap: [],
      ruleForm: this.initDefaults(),
      rules: {
        rechargeActivityName: [
          {
            required: true,
            message: this.$t('required', { field: '活动名称' })
          }
        ],
        rechargeDiscountList: [
          {
            required: true,
            type: 'array',
            message: this.$t('required', { field: '优惠选项' })
          }
        ],

        rechargeActivityPicture: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('required', { field: '活动图片' })
          }
        ],

        _dateRange: [
          {
            required: true,
            trigger: 'change',
            type: 'array',
            message: this.$t('required', { field: '活动时间' })
          }
        ],
        rechargeActivityContent: [
          {
            required: true,
            message: this.$t('required', { field: '活动内容' })
          }
        ]
      },

      rechargeFileList: []
    }
  },
  methods: {
    /**
     * 初始化主表及子表
     */
    initialize () {
      if (!this.$isEmpty(this.record)) {
        // 初始化主表数据
        this.ruleForm = this.record
        if (this.record.rechargeDiscountList) {
          this.record.rechargeDiscountList.forEach((data) => {
            const uuid = seed++
            this.itemMap.push({
              uuid,
              form: null
            })

            this.$nextTick(() =>
              this.broadcast('RechargeSubForm', 'subform.initialize', {
                uuid,
                data
              })
            )
          })
        }
      } else {
        this.handleAddClick()
      }
    },

    /**
     * 事件监听
     */
    addEventListeners () {
      this.$on('subform.created', (form) => {
        const target = this.itemMap.find((it) => it.uuid === form.uuid)
        if (target) {
          target.form = form
        }
      })

      this.$on('subform.removed', (form) => {
        this.itemMap.splice(
          this.itemMap.findIndex((it) => it.uuid === form.uuid),
          1
        )
      })
    },

    /**
     * 新增子表
     */
    handleAddClick () {
      this.itemMap.push({
        uuid: seed++,
        form: null
      })
    },

    /**
     * 提交表单数据
     */
    getRealFormData (data, model) {
      return this.$only(
        data,
        Object.keys(model).filter((key) => key.charAt(0) !== '_')
      )
    },

    /**
     * 提交主表及子表
     *
     * @param {Function} callback
     */
    submit () {
      // 校验主表
      this.$refs.ruleForm.validate((ok, values) => {
        if (ok) {
          // 校验子表
          let valid = true
          let count = 0
          let validValues = []

          if (this.items.length) {
            this.items.forEach((form) => {
              form.submit((ok, values) => {
                if (!ok) {
                  valid = false
                }
                validValues = validValues.concat(values)
                if (++count === this.items.length) {
                  this.$emit(
                    'submit',
                    valid,
                    this.getRealFormData(
                      {
                        ...this.ruleForm,
                        rechargeDiscountList: validValues
                      },
                      rechargeModel
                    )
                  )
                }
              })
            })
          } else {
            this.$emit(
              'submit',
              valid,
              this.getRealFormData(
                {
                  ...this.ruleForm,
                  rechargeDiscountList: []
                },
                rechargeModel
              )
            )
          }
        }
      })
    },
    updateRechargeFileList () {
      this.rechargeFileList = this.ruleForm.rechargeActivityPicture
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
    },
    // ---------------------------------------------------------- 上传图片 开始 ----------------------------------------------------------
    handleUploadSuccess (field, res, file, fileList) {
      if (res.result !== httpStatus.OK) {
        this.$message.error(res.message)
        return
      }

      this.ruleForm[field] = fileList
        .map((it) => (it.response && it.response.data) || it.name)
        .join(',')
    },

    handleUploadError (_, file, fileList) {
      this.$message.error(this.$t('fileUploadError'))
    },

    handleUploadRemove (field, file, fileList) {
      this.ruleForm[field] = fileList
        .map((it) => (it.response && it.response.data) || it.name)
        .join(',')
      this.updateCoverFileList()
    },

    updateCoverFileList () {
      this.rechargeFileList = this.ruleForm.rechargeActivityPicture
        .split(',')
        .filter(Boolean)
        .map((it) => {
          return {
            name: it,
            url: this.$V.staticBaseURL + it
          }
        })
    }
    // ---------------------------------------------------------- 上传图片 结束 ----------------------------------------------------------
  },
  computed: {
    items () {
      return this.itemMap.map((it) => it.form).filter(Boolean)
    },
    actionType () {
      return this.ruleForm[primaryKey] ? 'update' : 'create'
    },
    actionText () {
      return this.actionType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    }
  },
  created () {
    this.addEventListeners()
    this.initialize()
  },
  mounted () {
    this.updateRechargeFileList()
  },
  watch: {
    itemMap (val) {
      this.ruleForm.rechargeDiscountList = val
    },
    'ruleForm._dateRange' (val) {
      this.ruleForm.rechargeActivityStartTime = val[0] || ''
      this.ruleForm.rechargeActivityEndTime = val[1] || ''
    }
  }
}
</script>

<style scoped lang="scss">
.v-one-to-many__subWrapper.recharge {
  padding-left: 120px;
  .v-one-to-many-sub {
    border: 1px dashed #ccc;
  }
}
</style>
